package com.ias.agdis_r.util.sdcard;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;

import com.ias.agdis_r.manager.DataBaseManager;
import com.ias.agdis_r.module.ParameterModel;
import com.ias.agdis_r.util.S;

/**
 * 日志文件类
 * 
 * @author zhangsc
 * 
 */

public class WriteLog {
	

	private final String packageName = "IASDataBase/log";// SD卡存放数据文件的目录，可手动配置
	private String SDPATH=null;						//SD卡路径
	private String packPath=null;					//日志包路径
	private String logName1="HMT380_1.log";		//日志1名称
	private String logName2="HMT380_2.log";		//日志2名称
	private static WriteLog instance = null;	// 单例
	private String logCheck="";        //是否开启日志
	private double logSize=0;            //设定的日志文件大小(单位M)
	private File curUsedLogFile = null;
	private static final int maxCountNeedtoCheck = 100;
	private int curWriteTimes=0;

	private static final String LOG_CHECK_INFO = "1";
	private static final String LOG_CHECK_DEBUG = "2";
	
	public static WriteLog getInstance() {
		if (instance == null) {
			instance = new WriteLog();
		}
		return instance;
	}
	
	/**
	 * 获取日志配置文件的参数
	 * @return void
	 * @author by zhangsc
	 */
	
	public void getLogParam()
	{
		if(logCheck.equals(""))	//如果logCheck为空，则读取配置文件中的LOG_CHECK
		{
			logCheck= DataBaseManager.getInstance().getString(
				ParameterModel.T_LOG, ParameterModel.LOG_CHECK);
		}
		if(logSize==0)		//如果logSize为空，则读取配置文件中的LOG_SIZE
		{
			try {

				String readSize = DataBaseManager.getInstance().getString(
						ParameterModel.T_LOG, ParameterModel.LOG_SIZE);
				if(S.isNotEmpty(readSize))
				{
					logSize= Double.parseDouble(readSize);
				}

			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 获取日志文件的大小
	 * @param file 日志文件
	 * @return int  日志大小
	 * @author by zhangsc
	 */
	public double getFileSizes(File file){//取得文件大小 
		long s=0; 
		double fileSize = 0; 
		if (file.exists()) { 
		FileInputStream fis = null; 
		try {
			fis = new FileInputStream(file);
			s= fis.available();     //文件大小
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		finally
		{
			try {
				fis.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		fileSize = (double) s / 1048576;   //转换为单位为MB
		}
		return fileSize; 
		}

	/**
	 * 向日志文件中写日志
	 * @param string 日志信息
	 * @return void
	 * @author by zhangsc
	 */
	public void writeDebugLog(String log)
	{

		getLogParam();//获取日志参数
		System.out.println("测试日志DEBUG:" + log);
		if(!logCheck.equals(LOG_CHECK_DEBUG))//如果logCheck设置不为2，不写入日志
		{
			return;
		}
		SDPATH = SDcard.getSDPATH();				// 获取SD卡路径
		packPath=SDPATH+"/"+packageName;
		FileWriter fw=null;
		BufferedWriter bw=null;

		if (!SDPATH.equals("")) {			  //如果SD卡路径不为空
			if (!SDcard.isFileExist(packPath)) {// 如果目录不存在，则创建目录
				SDcard.creatSDDir(packPath);
			}
			File file=checkFile(packPath);   //获取日志文件
			if (null == file)
			{
				return;
			}
			try {
				//System.out.println("日志文件大小:"+getFileSizes(file));
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			try {
				fw=new FileWriter(file,true);
				bw=new BufferedWriter(fw);
				bw.write(S.getNowTime2()+log);			//写入日志
				bw.write("\r\n");                       //换行
				bw.flush();
				curWriteTimes++;

			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			finally
			{
				try {
					if(bw!=null)
					{
						bw.close();
					}
					if(fw!=null)
					{
						fw.close();
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		}
	}

	/**
	 * 向日志文件中写日志
	 * @param string 日志信息
	 * @return void
	 * @author by zhangsc
	 */
	public void writeLog(String log)
	{
	  getLogParam();//获取日志参数
	  System.out.println("log:"+log);
	  if(!logCheck.equals(LOG_CHECK_INFO)&&!logCheck.equals(LOG_CHECK_DEBUG))//如果logCheck设置为0，不写入日志
	  {
		  return;
	  }
	  
	  SDPATH = SDcard.getSDPATH();				// 获取SD卡路径
	  packPath=SDPATH+"/"+packageName;
	  FileWriter fw=null;
	  BufferedWriter bw=null;
	  
	  if (!SDPATH.equals("")) {			  //如果SD卡路径不为空
		  if (!SDcard.isFileExist(packPath)) {// 如果目录不存在，则创建目录
				SDcard.creatSDDir(packPath);
		  }		  		  
			  File file=checkFile(packPath);   //获取日志文件
			  if (null == file)
			  {
				  return;
			  }
			  try {
				//System.out.println("日志文件大小:"+getFileSizes(file));
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			  try {			 
					fw=new FileWriter(file,true);
					bw=new BufferedWriter(fw);
					bw.write(S.getNowTime2()+log);			//写入日志
					bw.write("\r\n");                       //换行
					bw.flush();
					curWriteTimes++;

				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				finally
				{
					try {
						if(bw!=null)
						{
							bw.close();
						}
						if(fw!=null)
						{
							fw.close();
						}
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
	
		  }
	}
	
	/**
	 * 判断日志文件的大小，始终向log1写入，
	 * 直到过大，再将log1改名为log2另存（有log2的情况下要先删除log2）
	 * @return
	 */
	
	private File checkFile(String path)
	{
		File logFile1 = null;	
		File logFile2 = null;			
		String filePath1 = null; 
		String filePath2 = null; 
		filePath1 = path+"/"+logName1;
		filePath2 = path+"/"+logName2;
		// 未有用过，或连续写超
		if (null == curUsedLogFile || curWriteTimes >= maxCountNeedtoCheck)	
		{
			curWriteTimes = 0;
			try
			{
				logFile1 = new File(filePath1);
				if(logFile1.exists())
				{
					if(getFileSizes(logFile1) >= logSize) 		// 1过大
					{
						logFile2 = new File(filePath2);			// 试2
						if(!logFile2.exists())	// 不存在2
						{
							logFile1.renameTo(logFile2);    	// 将1改为2另存
						}
						else	// 存在2
						{		// 直接删除2，再另存
							logFile2.delete();             		// 删除2
							logFile1.renameTo(logFile2);    	// 1另存为2
						}
					}
				}
	
				logFile1 = new File(filePath1); 	// 建1			
				logFile1.createNewFile();
				curUsedLogFile = logFile1;

			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			}
		}
		
		return curUsedLogFile;
	}
}
